const app = getApp();

Page({
  data: {
    downloads: [],
    writePhotosAlbumStatus: 0
  },
  onLoad: function () {
    var t = this;
    wx.getSetting({
      success: function (e) {
        void 0 === e.authSetting["scope.writePhotosAlbum"] ? t.setData({
          writePhotosAlbumStatus: 0
        }) : !0 === e.authSetting["scope.writePhotosAlbum"] ? t.setData({
          writePhotosAlbumStatus: 1
        }) : !1 === e.authSetting["scope.writePhotosAlbum"] && t.setData({
          writePhotosAlbumStatus: 2
        });
      }
    }), wx.showShareMenu({
      withShareTicket: !0
    });

    this.getSetting();
  },

  onShareAppMessage() {
    const { shareCover: imageUrl = '', shareTitle: title = '' } = this.data;
    return {
      title,
      path:'/cm_garbage_query/pages/search/search',
      imageUrl
    };
  },

  saveImageToAlbum: function (e) {
    var s = this;
    wx.downloadFile({
      url: this.data.downloads[e.currentTarget.dataset.downloadIndex],
      success: function (res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function () {
            s.setData({
              writePhotosAlbumStatus: 3
            })
            setTimeout(function () {
              s.setData({
                writePhotosAlbumStatus: 1
              });
            });
          },
          fail: res => {
            console.log('=======fail', res);
          }
        });
      }
    })
  },

  authorizeWritePhotosAlbum: function (t) {
    var e = this;
    wx.authorize({
      scope: "scope.writePhotosAlbum",
      success: function () {
        e.saveImageToAlbum(t);
      },
      fail: function () {
        e.setData({
          writePhotosAlbumStatus: 2
        });
      }
    });
  },

  openSetting: function (t) {
    void 0 === t.detail.authSetting["scope.writePhotosAlbum"] ? this.setData({
      writePhotosAlbumStatus: 0
    }) : !0 === t.detail.authSetting["scope.writePhotosAlbum"] ? (this.setData({
      writePhotosAlbumStatus: 1
    }), this.saveImageToAlbum(t)) : 0 == t.detail.authSetting["scope.writePhotosAlbum"] && this.setData({
      writePhotosAlbumStatus: 2
    });
  },

  getSetting() {
    app.util.request({
      module: 'cm_garbage_query',
      url: 'entry/wxapp/index',
      data: {
        op: 'getSetting'
      },
      showLoading: true,
      success: res => {
        console. log('=========res', res);
        const { share_cover: shareCover = '', share_title: shareTitle ='', thumb: downloads = []  } =  res.data.data;
       this.setData({
          downloads,
          shareCover,
          shareTitle
        })
      },
    });
  }
});